from rest_framework.decorators import api_view
from rest_framework.exceptions import ValidationError
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import serializers
import re


def phone_validator(value):
    if not re.match(r"^(1[3|4|5|6|7|8|9])\d{9}$", value):
        raise ValidationError('手机号格式错误')


class MessageSerializer(serializers.ModelSerializer):
    phone = serializers.CharField(label='手机号', validators=[phone_validator, ])


class LoginView(APIView):

    def post(self, request, *args, **kwargs):
        print(request.data)
        return Response({"status": True})


class MessageView(APIView):

    def get(self, request, *args, **kwargs):
        print(request.query_params)
        phone = request.query_params.get('phone')
        print(phone)

        # 获取手机号
        # 手机号格式校验
        ser = MessageSerializer(data=request.query_params)
        if not ser.is_valid():
            return Response({'status': False, 'message': '手机格式错误'})
        phone = ser.validated_data.get('phone')

        # 生成随机验证码
        import random
        random_code = random.randint(1000, 9999)

        # 将验证码发送到手机上，需购买服务器发送短信
        # xxx.send_message(phone, random_code)

        # （单线程）将手机号和验证码存储到redis中，60S过期
        # import redis
        # pool = redis.ConnectionPool(host='xxx', port=6379)
        # conn = redis.Redis(connection_pool = pool)
        # conn.set(phone, random_code, ex = 60)

        # （多线程）将手机号和验证码存储到redis中，60S过期

